<?php

class M_user extends CI_Model{
	 
	public function getUser($v){
		
		$this->db->where('usertype', $v->usertype);
		$this->db->where('username', $v->username);
		$query = $this->db->get('users');
		
			
		if($query->num_rows == 1)
		{
			$row = $query->row();
			
			if($this->validate_password($row->password, $v->password)){
				if($row->usertype == 'student'){
					$q = $this->db->select('user_id, student_profiles.course_id, course_code, id_no, firstname, lastname, middlename, courses.course_id')->from('student_profiles')->join('courses', 'courses.course_id = student_profiles.course_id', 'left')->where('user_id', $row->id)->get();
					$r = $q->row();
					
					$userdata = array(
						'userid' => $row->id,
						'usertype' => $row->usertype,
						'id_no' => $r->id_no,
						'logged_in' => true,
						'name' => $r->lastname.', '.$r->firstname.' '.substr($r->middlename, 0, 1),
						'course_id' => $r->course_id,
						'course_code' => $r->course_code
					);
					
				}
				else {
					$userdata = array(
						'userid' => $row->id,
						'usertype' => $row->usertype,
						'logged_in' => true
					);
				}
				
					
				$this->session->set_userdata($userdata);
				return true;
			}
		}
		else
			return false;
		
	}
	
	public function add_user($v){
		$password = $this->hash_password($v->password);
		$v->password = $password;
		
		$user_data = array(
				'username' => $v->username,
				'password' => $v->password,
				'usertype' => $v->usertype,
				'created' => NOW
			);
		$this->db->insert('users', $user_data);
		return $this->db->affected_rows() > 0 ? TRUE : FALSE;
	

	}
	

	public function get_user_password($user_id){
		$this->db->select('password');
		$this->db->where('id', $user_id);
		$query = $this->db->get('users');
		return $query->row('password');
	}
	
	public function change_password($password, $user_id){
		$data = array(
			'password' => $this->hash_password($password),
			'updated' => NOW
		);
		
		$this->db->where('id', $user_id);
		if($this->db->update('users', $data))
			return true;
		else
			return false;
	}

	public function validate_password($hashed_password, $password)
    {
        $salt = substr($hashed_password, 0, 64);
        $hash = substr($hashed_password, 64, 64);

        $password_hash = hash('sha256', $salt . $password);
        
        return $password_hash == $hash;
    }
	
	public function hash_password($password)
    {
        $salt = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
        $hash = hash('sha256', $salt . $password);

        return $salt . $hash;
    }
	
	






	
	
}

?>